<template>
  <el-dialog
      title="添加信息"
      v-model="dialogVisibleAdd"
      width="800px"
      @close="resetFormData"
  >
    <el-form ref="addDataForm" :model="addData" label-width="180px">
      <el-form-item
          v-for="(value, key) in add_reportInfo"
          :key="key"
          :label="value.verbose_name"
          :prop="key">
        <component
            :is="inputComponentForType(value, key)"
            v-model="addData[key]"
            v-bind="value.componentProps || {}"
        >
          <!-- 当组件为el-select时，渲染options -->
          <template v-if="inputComponentForType(value, key) === 'el-select'">
            <el-option
                v-for="option in value.choices"
                :key="option"
                :label="option"
                :value="option"
            ></el-option>
          </template>
        </component>
      </el-form-item>

      <el-form-item label="相关人员">
        <div v-for="(author, index) in addData['authors']" :key="index">
          _({{ author.role }}){{ author.account }}_&&
        </div>
        <el-button @click="addAuthor">添加人员</el-button>
        <el-button @click="delAuthor">删除人员</el-button>
      </el-form-item>
      <el-form-item label="分数权重">
        <div>
          {{ addData['score_weights'] }}
        </div>
      </el-form-item>
      <el-form-item label="填写说明">
        {{add_instructions}}
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :loading="SubmitAddLoading"
                   :disabled="SubmitAddLoading"
                   @click="handleSubmitAdd">{{ SubmitAddLoading ? '正在添加' : '确认' }}
        </el-button>
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <AddAuthor ref="addAuthorComponent" :Type="'add'"/>
</template>
<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage} from "element-plus";
import AddAuthor from "@/components/Main/ReportManagement/AddAuthor.vue";
import global, {jsonApi} from "@/global.js";


const props = defineProps({
  tableType: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    required: true
  }
});
const accessToken = localStorage.getItem('access_token');
const refreshToken = localStorage.getItem('refresh_token');
const reportInfo = ref({});
const add_reportInfo = ref({});
// 填写说明
const add_instructions = ref('');
const storedReportInfo = localStorage.getItem('reportinfo');
// 添加数据弹窗控制
let dialogVisibleAdd = ref(false);
let addData = reactive({});
const addDataForm = ref(null);
const SubmitAddLoading = ref(false);
onMounted(() => {
  eventBus.on('report-form-table-add', handleReportFormTableAdd);
  eventBus.on('author-add', handleReportFormTableAuthorsAdd);
});

onBeforeUnmount(() => {
  eventBus.off('report-form-table-add', handleReportFormTableAdd);
  eventBus.on('author-add', handleReportFormTableAuthorsAdd);
});
const handleSubmitAdd = async () => {
  SubmitAddLoading.value = true;
  // 在此处实现添加数据的逻辑
  console.log('添加数据的逻辑在这里实现');
  // 在这里你可以处理表单提交逻辑
  const accessToken = localStorage.getItem('access_token');
  const refreshToken = localStorage.getItem('refresh_token');
  addData['Report'] = props.tableType;
  //去除this.newData.author中元素为空的元素
  try {
    // 尝试使用当前的access_token获取数据
    let api_url = '';
    if (props.isAdmin) {
      api_url = '/reportmanager/addforadmin/';
    } else {
      api_url = '/reportmanager/add/';
    }
    const response = await jsonApi(api_url, JSON.stringify(addData));

    const data = await response.json();

    // 检查返回的数据是否包含错误信息，表明token可能无效或过期
    if (response.status === 201 || response.status === 200) {
      refresh();
      SubmitAddLoading.value = false;
      dialogVisibleAdd.value = false;

    } else {
      //执行父组件的方法
      // dialogVisibleAdd = false;
      ElMessage({
        type: 'error',
        message: data.error
      });
      SubmitAddLoading.value = false;

    }

    // 如果没有错误，则返回数据


  } catch (error) {
    // 网络错误或其他非token导致的错误
    SubmitAddLoading.value = false;
    throw error;
  }
}
// 使用defineEmits声明事件
const emit = defineEmits(['refresh-table']);

function refresh() {
  emit('refresh-table', {});
}

// Methods
const getReportInfo = async () => {
  reportInfo.value = JSON.parse(storedReportInfo)[props.tableType];
  add_instructions.value =reportInfo.value.input_info;
  //获取增加时的字段
  add_reportInfo.value = reportInfo.value;
  const add_excludeFields = ['id', 'model_name', 'max_score', 'authors', 'score_weights', 'score', 'modified_time', 'attachment', 'reviewer', 'revstatus', 'created_time', 'review_time','input_info'];
  add_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (add_reportInfo.value.hasOwnProperty(field)) {
      delete add_reportInfo.value[field];
    }
  });
  for (let key in add_reportInfo.value) {
    if (add_reportInfo.value[key]["type"] ==='BooleanField') {
      addData[key] = false;
    }else{
      addData[key] = null;
    }

  }
  const userinfoString = localStorage.getItem('userinfo')
  const userinfo = JSON.parse(userinfoString);
  console.log(userinfo['username'])
  addData['authors'] = []
  addData['score_weights'] = []
  if (addData['is_first_unit']) {
    addData['is_first_unit'] = true;
  }

}
//刷新表格获取新数据

const handleReportFormTableAdd = () => {
  dialogVisibleAdd.value = true;
  getReportInfo()
};
const handleReportFormTableAuthorsAdd = (info) => {
  //去除info中key为name的项
  const userinfoString = localStorage.getItem('userinfo')
  const userinfo = JSON.parse(userinfoString);
  if (addData['authors'].length === 0) {
      if (props.isAdmin) {
        if (info.role !== '负责人') {
          ElMessage({
            type: 'error',
            message: '第一位只能是负责人，已修改'
          });
        }
        addData['authors'].push({"name": info.name,"account": info.account, "role": '负责人'});
      } else {
        if (info.role !== '负责人' || info.account !== userinfo['username']) {
          ElMessage({
            type: 'warning',
            message: '你必须添加自己为第一顺位，且为负责人，已经帮您修改'
          });
        }
        addData['authors'].push({"name":  userinfo['name'],"account": userinfo['username'], "role": '负责人'});
      }

      addData['score_weights'].push(Number(info.weight));
    } else {
      if (info.role === '负责人') {
        ElMessage({
          type: 'error',
          message: '只能添加一个负责人'
        });
        //addData['score_weights']的和大于1
      } else if (addData['score_weights'].reduce((a, b) => a + b, 0) > 1) {
        ElMessage({
          type: 'error',
          message: '分数权重之和不能大于1'
        });
      } else if (addData['authors'].some(item => item.account === info.account)) {
        ElMessage({
          type: 'error',
          message: '不能添加重复的作者'
        });
      } else {
        addData['authors'].push({"name": info.name,"account": info.account, "role": info.role});
        addData['score_weights'].push(Number(info.weight));
      }
      // }else if(addData['score_weights']){
      //   addData['authors'].push({"account": info.account, "role": info.role});
      //   addData['score_weights'].push(Number(info.weight));
      // }

    }

  }
  ;
const addAuthorComponent = ref(null);
const addAuthor = () => {
    if (addAuthorComponent.value && typeof addAuthorComponent.value.open === 'function') {
      addAuthorComponent.value.open(props.isAdmin, addData['authors']);
    } else {
      console.error('addAuthorComponent.open is not a function');
    }
  };
const delAuthor = () => {
    addData['authors'].pop();
    addData['score_weights'].pop();
  };
const inputComponentForType = (value, key) => {
    const componentMap = {
      'CharField': 'el-input',
      'IntegerField': 'el-input',
      'DateTimeField': 'el-date-picker',
      'JSONField': 'el-textarea', // 使用文本域展示JSON字符串，并考虑设置为只读
      'BooleanField': 'el-switch',
      'URLField': 'el-input',
      'TextField': 'el-input'
    };

    // 如果value.choices存在，则返回el-select组件并且附带options
    if (value.choices !== null) {
// 使用choice.label作为label，choice.value作为value
//       console.log(value.choices,value.type)
      return 'el-select'
    } else {
      // 直接返回组件类型，如果未找到则返回'未知类型'
      return componentMap[value.type] || 'el-input';
    }


  };
// 重置表单数据
const resetFormData = () => {
    getReportInfo();
  };

function showError(message, error, duration) {
    console.error(message, error);
    // 实现错误展示逻辑，例如使用通知组件
  }
</script>
<style scoped>

</style>